package com.news.util;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * Created by lingzhiyuan.
 * Date : 15/10/10.
 * Time : 下午7:40.
 * Description:
 */
public class FileUtil {

    public static String save(MultipartFile multipartFile, String fileUUID, String path) {
        String originalFilename = multipartFile.getOriginalFilename();
        String contentType = multipartFile.getContentType();
        if (!(originalFilename.endsWith(".html") || originalFilename.endsWith(".xhtml") || originalFilename.endsWith(".shtml"))) {
            throw new RuntimeException("不支持的文件后缀: " + originalFilename);
        }

        String fileType = ".html";

        String uuid;
        if (StringUtils.isEmpty(fileUUID)) {
            //自动生成一个文件名，使用UUID字符串，并且去掉横线"-"
            uuid = UUID.randomUUID().toString();
        } else {
            uuid = fileUUID.replaceAll("-", "");
        }

        if (multipartFile != null && !multipartFile.isEmpty()) {
            try {
                String dir = path;

                File fileDir = new File(dir);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }

                String fileName = uuid + fileType;
                String filePath = dir + File.separator + fileName;
                File file = new File(filePath);
                byte[] bytes = multipartFile.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
                stream.write(bytes);
                stream.close();

                String uploadDir = Paths.get(path).getFileName().toString();

                String urlPath = "/" + uploadDir + "/" + fileName;
                return urlPath;
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("文件读写错误: " + originalFilename);
            }
        }

        return null;
    }

}
